#!/bin/bash
function install_memcached() {
    echo "安装memcached" >>$logs_file
    mem_total=`cat /proc/meminfo |grep -i MemTotal|awk '{print $2}'`
    initmcacheSize=`expr $mem_total / 10 / 1024`
    if [ $initmcacheSize -lt 128 ];then
        initmcacheSize=128
    fi
        
    mcacheSize=
    while [[ ! $mcacheSize =~ ^[1-9][0-9]*$ ]]
    do
        mcacheSize=$(whiptail --backtitle "Author: Elvis" --title "$cacheSize_title" --inputbox \
        "$cacheSize_text" 12 60 "$initmcacheSize" 3>&1 1>&2 2>&3)
        exitstatus=$?
        if [ "$exitstatus" != "0" ];then
           return 1
        fi
        
        if [[ ! $mcacheSize =~ ^[1-9][0-9]*$ ]];then
           whiptail --backtitle "Author: Elvis" --title "$error_message" --msgbox "$cachePort_promtp" 10 60
           sleep 0.3
        fi
    done
    mcacheSize=`echo $mcacheSize`
    
    {
    echo 1
    sleep 1
    msg="$cache_beginIns"
    echo "`date "+%Y-%m-%d %H:%M:%S"` $msg" >>$logs_file
    echo -e "XXX\n30\n$msg\nXXX"
    echo 30
    if [ "$die_network" == "true" ];then
        rpm -ivh $workHome/packages/memcached/el$system_ver/*.rpm >>$logs_file 2>&1
    else
        yum install -y memcached >>$logs_file 2>&1
    fi
    
    msg="$cacheSize_set"
    echo "`date "+%Y-%m-%d %H:%M:%S"` $msg" >>$logs_file
    echo -e "XXX\n60\n$msg\nXXX"
    echo 60
    sleep 1
    sed -i "s/CACHESIZE.*/CACHESIZE=\"$mcacheSize\"/" /etc/sysconfig/memcached
    
    msg="$cache_start"
    echo "`date "+%Y-%m-%d %H:%M:%S"` $msg" >>$logs_file
    echo -e "XXX\n90\n$msg\nXXX"
    echo 90
    sleep 1
    service memcached restart >/dev/null 2>>$logs_file
    
    echo -e "XXX\n100\ndone！！！\nXXX"
    echo 100
    sleep 1 
    } | whiptail --backtitle "Author: Elvis" --title "$cache_gauge" --gauge " " 6 60 0
    
    sleep 0.30
    #判断是否启动
    memPid=`pidof memcached`
    if [ -n "$memPid" ];then
        msg="${cache_success}${mcacheSize}M"
        echo "`date "+%Y-%m-%d %H:%M:%S"` $msg" >>$logs_file
        whiptail --backtitle "Author: Elvis" --title "$info_message" --msgbox "$msg" 10 70
    else
        echo "$cache_failed" >>$logs_file
        whiptail --backtitle "Author: Elvis" --title "错误" --msgbox "$cache_failed" 10 70
    fi
    sleep 0.30 
}